import { uniConfig } from "../config/UniConfig";
import { Databus } from "../core/Databus";
import { PlatformSetting } from "../platform/PlatformSetting";

const databus = Databus.Instance();
// 资产列表
export function querySettingList(userId: string, setId: string, setType: number) {
  if (PlatformSetting.isHTML5()) {
    return;
  }
  const url = `${uniConfig.apiUrl}/unigame/setting/list`;
  const xhr = new XMLHttpRequest();
  console.log('request url ', url);
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
      console.log(xhr.responseType, xhr.response, xhr.responseText);
      var response = JSON.parse(xhr.responseText);
      for (const st of response.settings) {
        if (st.setType === 1 && st.setKey === 'coin') {
          databus.updateEarnCoin(st.setValue);
        }
        if (st.setType === 2 && st.setKey === 'currentBarrierLevel') {
          databus.hurdles.initLevel(+st.setValue);
        }
        if (st.setType === 3 && st.setKey === 'maxContinueHitBall') {
          databus.maxContinueHitBall = +st.setValue;
        }
        if (st.setType === 4 && st.setKey === 'musicSetting') {
          databus.updateBgMusic(+st.setValue);
        }
        if (st.setType === 5 && st.setKey === 'bag') {
          databus.updateParseBagPack(st.setValue);
        }
        if (st.setType === 6 && st.setKey === 'gameLock') {
          databus.GameLockConfig.parseValue(st.setValue);
        }
      }
    }
  };
  xhr.open("GET", url + `?user_id=${userId}&set_id=${setId}&set_type=${setType}&game_name=billiard`, true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send();
}

export function updateSetting(userId: string, setId: string, setType: number, setKey: string, setValue: string) {
  if (PlatformSetting.isHTML5()) {
    return;
  }
  const url = `${uniConfig.apiUrl}/unigame/setting/update`;
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
      console.log(xhr.responseType, xhr.response, xhr.responseText);
      var response = JSON.parse(xhr.responseText);
    }
  };
  xhr.setRequestHeader("Content-Type", "application/json");

  xhr.open("POST", url, true);
  const data = {
    user_id: +userId,
    set_id: +setId,
    set_type: setType,
    set_key: setKey,
    set_value: setValue,
  };
  xhr.send(JSON.stringify(data));
}